package com.docker.sys.role.rolePerm;

import com.docker.core.mvc.service.BaseService;
import com.docker.sys.permission.PermissionService;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Okv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import kit.docker.convert.RecordKit;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @Author ldl
 * @Create 2020/09/18 018 15:35
 */
public class RolePermService extends BaseService {

    @Inject
    private RolePermDao rolePermDao;

    @Inject
    private PermissionService permissionService;

    public List<Record> bindList() {
        return rolePermDao.bindList();
    }

    public void deletePerm(String permId) {
        rolePermDao.deletePerm(permId);
    }

    public List<Record> userPerm(String appId, boolean isSuperAdmin, String roleId) {
        Okv cond = Okv.create()
                .set("p.status_flag = ", "1");
        if (isSuperAdmin) {
            return permissionService.authList(Okv.by("cond", cond).set("app_id", appId));
        }
        cond.set("rp.role_id = ", roleId);
        return rolePermDao.authList(Okv.by("cond", cond).set("app_id", appId));
    }

    public List<Record> tree(Okv cond) {
        List<Record> perms = rolePermDao.tree(cond);
        List<Record> tree = new ArrayList<>();
        LinkedHashMap<String, List<Record>> map = new LinkedHashMap<>();
        for (Record perm : perms) {
            String controllerName = perm.getStr("controller_name");
            if (StrKit.isBlank(controllerName)) {
                controllerName = "未命名控制器";
            }
            List<Record> sperms;
            if (map.containsKey(controllerName)) {
                sperms = map.get(controllerName);
            } else {
                sperms = new ArrayList<>();
            }
            sperms.add(perm);
            map.put(controllerName, sperms);
        }
        for (String key : map.keySet()) {
            Record perm = new Record();
            perm.set("controller_name", key);
            perm.set("list", map.get(key));
            tree.add(perm);
        }
        return tree;
    }

    public boolean save(String roleId, String permId) {
        return rolePermDao.save(RecordKit.objectToRecord(new RolePermBean(getUUID32(), roleId, permId)));
    }

    public boolean delete(String roleId, String permId) {
        rolePermDao.delete(roleId, permId);
        return true;
    }

}
